<template>
	<div class="login-container">
        <!-- 导航栏 -->
        <TmallNavBar>
            <template #default>密码登录</template>
            <template #right>
				<i class="icon iconfont icon-shouye1" @click="$router.push({path: '/'})"></i>
			</template>
        </TmallNavBar>

        <!-- logo -->
		<div class="logo-wapper" @click="goto('/')">
			<van-image :src="loginImage" class="logo" />
			<div class='text'>三叉戟商城，精品购物品牌</div>
		</div>
		
        <!-- 表单 -->
		<div class="login-box">
			<!-- 基础表单校验 -->
			<van-form @submit="onSubmit">
                <van-cell-group inset>
                    <!-- 用户名 -->
                    <van-field
                        v-model="formData.username"
                        :label-width="labelWidth"
                        name="用户名"
                        label="用户名"
                        placeholder="请输入用户名"
                        left-icon="manager"
                        :rules="[{ required: true, message: '请输入用户名' }]"
                    />
                    
                    <!-- 密码 -->
                    <van-field
                        v-model="formData.password"
                        :label-width="labelWidth"
                        type="password"
                        name="密码"
                        label="密码"
                        left-icon="lock"
                        placeholder="请输入密码"
                        :rules="[{ required: true, message: '请输入密码' }]"
                    />
                </van-cell-group>
                
                <!-- 登录按钮 -->
                <div style="margin: 16px">
                    <van-button
                        type="primary"
                        native-type="submit"
                        round
                        block
                        color="#27BA9B"
                    >
                        登&nbsp;&nbsp;录
                    </van-button>
                </div>
			</van-form>

			
			<!-- 底部 -->
			<div class="footer-wapper">
				<div @click="goto('/messageLogin')">短信登录</div>
				<div @click="goto('/register')" style="font-size: 18px;color: #E83915;">还没有账户</div>
				<div @click="goto('/forgotPassword')">找回密码</div>
			</div>
			
			<!-- 第三方登录 -->
			<div class="third-wapper">
				<div class="third-line">
					<div class="single-line">
						<div class="line"></div>
					</div>
					<div style="font-size: 13px;">第三方登录</div>
					<div class="single-line">
						<div class="line"></div>
					</div>
				</div>
				
				<div class="third-icons-wapper">
					<van-image :src="qqImage" class="third-ico" @click="thirdLogin('qq')" />
					<van-image :src="weiboImage" class="third-ico" @click="thirdLogin('sinaweibo')" style="margin-left: 40px;" />
					<van-image :src="wxImage" class="third-ico" @click="thirdLogin('weixin')" style="margin-left: 40px;" />
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref } from "vue"
import { useUserStore } from '@/store/modules/user'
import { useCartStore } from '@/store/modules/cart'
import {useRoute, useRouter} from 'vue-router'
import loginImage from '@/assets/images/logo.png'
import qqImage from '@/assets/images/qq.png'
import weiboImage from '@/assets/images/weibo.png'
import wxImage from '@/assets/images/wx.png'
import { showSuccessToast } from 'vant'

// 输入框标签宽度
const labelWidth = ref('50px')

// 用户存储
const userStore = useUserStore()

// 路由器
const router = useRouter()

// 路由
const route = useRoute()

// 购物车存储
const cartStore = useCartStore()

// 提交数据
const formData = reactive({
	username: '',
	password: ''
})

// 处理登录
const onSubmit = async () => {
    await userStore.login(formData)

    // 获取购物车商品
    await cartStore.getCartList()
	
    showSuccessToast('欢迎回来')
    setTimeout(() => {
        const redirectUrl = decodeURIComponent(route.query.redirect)
			
		// 登录成功后，跳转url不为空并且不等于退出页，则跳转至跳转url，否则跳转至首页
		// 必须跳转至我的页面的redirectUrl
		const unRedirectUrls = [
			'/userSet',
			'/passwordLogin',
			'/messageLogin',
			'/forgotPassword',
			'/register',
		]

		if (redirectUrl == "undefined" || redirectUrl == "" || redirectUrl == 'null'|| unRedirectUrls.includes(redirectUrl)) {
			router.push({path: '/'})
		} else {
			const params = queryURLparams(redirectUrl)
			router.push({path: redirectUrl, query: params})
		}
    }, 1000)
}

// 第三方登录
const thirdLogin = (platform) => {
}

// 解下URL参数
const queryURLparams = (url) => {
    let obj = {}
    if (url.indexOf('?') < 0) return obj
    let arr = url.split('?')
    url = arr[1]
    let array = url.split('&')
    for (let i = 0; i < array.length; i++) {
        let arr2 = array[i]
        let arr3 = arr2.split('=')
        obj[arr3[0]] = arr3[1]
    }
    return obj
}




// -------------------------- 使用微信绑定手机号登录功能开始 --------------------------
const code = ref('')
// 手机号实时验证
// 目前该接口针对非个人开发者，且完成了认证的小程序开放
const onGetPhoneNumber = async (e) => {
	// 获取微信绑定的手机号，即：手机号实时验证组件
	// https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getRealtimePhoneNumber.html
	console.log(e.detail.code)  // 动态令牌
	console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
	console.log(e.detail.errno)  // 错误码（失败时返回）

	const result = await wx.login()
	console.log('wx code =', result);
	if (result.errMsg != 'login:ok') {
		return
	}
	
	// 登录
	await userStore.login(result.code, 3)
	showSuccessToast('欢迎回来')
	
	setTimeout(() => {
	}, 1000)
}


// 获取用户信息但由于该接口在高本版已被回收，因此不用
// const getUserProfile = () => {
// 	uni.showLoading({
// 		title: '登录中...'
// 	});
	
// 	// 获取用户信息但由于该接口在高本版已被回收，因此不用
// 	wx.getUserProfile({
// 		desc: '用于完善会员资料',
// 		success: (res) => {
// 			let {encryptedData, iv, rawData, signature, userInfo} = res
// 			console.log(res)
// 			uni.login({
// 				provider: 'weixin',
// 				success: (result) => {
// 					// code: "021UZLGa1LnRtC0UmDGa1y4bEH1UZLG3"
// 					// errMsg: "login:ok"
// 					console.log(result)
// 					//发送数据到后台完成登录
// 					const data = {username: userInfo.nickName, nickname: userInfo.nickName, avatar: userInfo.avatarUrl}
// 					console.log(data)
// 					uni.hideLoading()
// 					uni.showToast({
// 						title: "登录成功",
// 						success: () => {
// 							setTimeout(() => {
// 								uni.switchTab({
// 									url:'/pages/me/me'
// 								})
// 							}, 1000)
// 						}
// 					})
// 				}
// 			})
// 		},
// 		fail(err) {
// 			console.log(err)
// 		}
// 	})
// }

// 跳转
const goto = (url) => {
    router.push({path: url})
}
</script>

<style scoped lang="scss">
.login-container {
    background: ghostwhite;
    height: calc(100vh - 47px);
}
.logo-wapper {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	margin-top: 47px;
	margin-bottom: 60px;
    padding-top: 40px;
	.logo {
		width: 175px;
		height: 75px;
	}
	.text {
		font-size: 13px;
		color: #666;
	}
}
.footer-wapper {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	margin-top: 10px;
	color: #909399;
}

// 第三方登录
.third-wapper {
	width: 100%;
	margin-top: 30px;
	.third-line {
		display: flex;
		flex-direction: row;
		justify-content: center;
		.single-line {
			padding: 8px 10px;
			width: 25%;
			align-items: center;
			.line {
				height: 1px;
				background-color: #DBDBDA;
			}
		}
	}
	.third-icons-wapper {
		margin-top: 15px;
		display: flex;
		flex-direction: row;
		justify-content: center;
		.third-ico {
			width: 30px;
			height: 30px;
		}
		.third-btn-ico {
			background-image: url(@/assets/images/wx.png);
			width: 30px;
			height: 30px;
			background-color: #FFFFFF;
			background-size: 30px 30px;
			background-repeat: no-repeat;
			border: none;
			padding: 0;
			border-radius: 50%;
		}
	}
}

.login-box {
    padding: 0 10px;
}
</style>
